const fs = require('fs');

const path = require('path');

const { userTable } = require('../../schemas/index');

const { getResJson, formatTime } = require('../../assets/util');

const { HOST } = require('../../assets/config');

/**
 * 查询用户
 * @param {Function} callback 回调函数
 */
exports.searchUser = (callback) => {
    userTable.find({}, (err, data) => {
        let resJson = {};
        if (err) {
            resJson = getResJson(data, '查询失败', false);
        } else {
            resJson = getResJson(data, '查询成功');
        }
        callback(resJson);
    })
}

/**
 * 添加用户
 * @param {Object} 参数
 * @param {Function} callback 回调函数
 */
exports.addUser = (params, callback) => {
    userTable.find({ 'netName': params.netName }, (err, data) => {
        if (data.length > 0) {
            let resJson = getResJson(data, '网名重复', false);
            callback(resJson);
            return;
        }
        params.addtime = formatTime();
        userTable.create(params, (err, users) => {
            let resJson = {};
            if (err) {
                resJson = getResJson(users, '添加失败', false);
            } else {
                resJson = getResJson(users, '添加成功');
            }
            callback(resJson);
        })
    })
}

/**
 * 删除用户
 */
exports.deleteUser = (params, callback) => {
    // 拿到项目根目录
    const rootpath = path.join(__dirname, '../..');
    userTable.findOne({ '_id': params._id }, (err, userInfo) => {
        let wechatImg = userInfo.wechatImg;
        let path = wechatImg.replace(new RegExp(HOST, 'g'), rootpath);
        userTable.deleteOne({ '_id': params._id }, (error, data) => {
            let resJson = {}
            if (error) {
                resJson = getResJson(data, '删除失败', false);
            } else {
                // 删除掉该用户的微信图
                fs.unlinkSync(path);
                resJson = getResJson(data, '删除成功');
            }
            callback(resJson);
        })
    })
}

/**
 * 修改用户信息
 */

exports.editUser = (params, callback) => {
    userTable.update({ '_id': params._id }, params, (err, data) => {
        let resJson = {}
        if (err) {
            resJson = getResJson(data, '修改失败', false);
        } else {
            resJson = getResJson(data, '修改成功');
        }
        callback(resJson)
    });
}